﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace scomA2Proj
{
    public class MulticellBuffer
    {
        private int index = -1;
        private int numCells = 0;
        private string[] bufferArr;

        /// <summary>
        /// Constructor for multicell buffer.
        /// </summary>
        /// <param name="numCells"></param>
        public MulticellBuffer(int numCells)
        {
            bufferArr = new string[numCells];
            this.numCells = numCells;
        }


        /// <summary>
        /// Blocking get from multicell buffer. If there are no items in the buffer, this will block indefinately.
        /// </summary>
        /// <returns>The current item pointed to in the buffer.</returns>
        public string getItem()
        {
            string res = null;
            
            lock (this)
            {
                while (isEmtpy())
                {
                    Monitor.Wait(this);
                }
                res = bufferArr[index];
                index--;
                Monitor.PulseAll(this);
            }
            
            return res;
        }

        /// <summary>
        /// Blocking put item. If the buffer is full, this will block indefinately.
        /// </summary>
        /// <param name="item"></param>
        public void putItem(string item)
        {
            lock (this)
            {
                while (isFull())
                {
                    Monitor.Wait(this);
                }
                index++;
                bufferArr[index] = item;
                
                Monitor.PulseAll(this);
            }
            
        }

        /// <summary>
        /// Checks if the buffer is empty.
        /// </summary>
        /// <returns>True if empty</returns>
        public bool isEmtpy()
        {
            return index == -1;
        }

        /// <summary>
        /// Checks if the buffer is full.
        /// </summary>
        /// <returns>True if full</returns>
        public bool isFull()
        {
            return index == numCells - 1;
        }
    }
}
